package com.yi.wood.service.impl;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.dao.RoleDao;
import com.yi.wood.dao.UserRoleDao;
import com.yi.wood.entity.Role;
import com.yi.wood.service.RoleService;
import com.yi.wood.service.exception.BusinessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author MoYi
 * create date 2019/4/6 14:57
 */
public abstract class AbstractRoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Resource
    private UserRoleDao userRoleDao;

    @Override
    public Role addData(Role role) {
        return roleDao.save(role);
    }

    @Override
    public void delData(Long roleId) {
        // 检查角色是否有被引用
        int count = userRoleDao.countByRoleIdEquals(roleId);
        if (count <= 0){
            roleDao.deleteById(roleId);
            return;
        }
        throw new BusinessException(new Result(ResultCodeEnum.CANNOT_DELETE,null));
    }

    @Override
    public Role updateData(Role role) {
        return roleDao.save(role);
    }

    @Override
    public List<Role> queryAllRole(String name, Integer status) {
        Role role = new Role();
        ExampleMatcher exampleMatcher;
        Example<Role> example = Example.of(role);
        if (!StringUtils.isEmpty(name)){
            role.setName(name);
            exampleMatcher = ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(role, exampleMatcher);
        }
        if (!Objects.isNull(status)){
            role.setStatus(status);
            example = Example.of(role);
        }
        return roleDao.findAll(example);
    }

    @Override
    public List<Role> queryUserRole(Long userId) {
        return roleDao.queryRoleByUserId(userId);
    }

    @Override
    public Page<Role> pageDataList(Example<Role> example, Pageable pageable) {
        return null;
    }
}
